package com.rqf.ls.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.oreilly.servlet.ParameterNotFoundException;
import com.rqf.common.base.PathManager;
import com.rqf.common.base.ProjectInfor;
import com.rqf.ls.service.IFileUploadService;
import com.rqf.ls.service.IRegisterService;
import com.rqf.ls.service.IVerifyService;
import com.server.password.MyBase64;
import com.server.web.JSONSerielizer;
import com.server.web.OutputUtil;

/**
 * 注册相关
 * @author ServerZhang
 * @date 2016年3月16日
 */
@Controller
@RequestMapping("register")
public class RegisterController {
	
	@Autowired
	private IRegisterService registerService;
	@Autowired
	private IVerifyService verifyService;
	@Autowired
	private IFileUploadService fileUploadService;
	
	 /**
	 * 注册页面
	 * @param request
	 * @param response
	 * @return
	 * @author ServerZhang
	 * @date 2016年3月16日
	 */
	@RequestMapping("")
	public ModelAndView registerPage(HttpServletRequest request, 
			HttpServletResponse response){
		ModelAndView mv = new ModelAndView();
		//TODO 
		return mv;
	}
	
	 /**
	 * 发送手机验证码
	 * @param response
	 * @author ServerZhang
	 * @date 2016年3月16日
	 */
	@RequestMapping("sendCode/{phoneNo}")
	public void sendCode(HttpServletResponse response, 
			@PathVariable String phoneNo){
		//如果前端验证了手机输入的合法性，这里不再验证
		
		String sendCode = registerService.sendCode(phoneNo);
		if (!StringUtils.isEmpty(sendCode)) {
			//将验证码及发送时间缓存到服务器内存当中
			verifyService.addRegisterCode(phoneNo, sendCode);
		}else {
		}
	}
	
	 /**
	 * 手机验证码匹配
	 * @param request
	 * @param response
	 * @param phoneNo
	 * @param code
	 * @author ServerZhang
	 * @date 2016年3月17日
	 */
	@RequestMapping("verify/{phoneNo}/{code}")
	public void verify(HttpServletRequest request, 
			HttpServletResponse response,@PathVariable String phoneNo,
			@PathVariable String code){
		Boolean isSuccess = false;
		Map<String, Object> registerCode = verifyService.getRegisterCode(phoneNo);
		if (registerCode != null) {
			Object codeObj = registerCode.get("code");
			if (code.equals(codeObj)) {
				isSuccess = true;
			}
		}
		OutputUtil.returnJsonp(request, response, isSuccess.toString());
	}

	 /**
	 * 开始注册
	 * @param request
	 * @param response
	 * @author ServerZhang
	 * @date 2016年3月17日
	 */
	@RequestMapping("confirm/{phoneNo}")
	public void reister(HttpServletRequest request, 
			HttpServletResponse response,@PathVariable String phoneNo){
		
		String password = request.getParameter("password");
		
		Map<String,Object> userMap = new HashMap<String, Object>();
		
		Boolean isSuccess = true;
		String errorInfo = "操作失败";
		
		if (StringUtils.isEmpty(phoneNo) || StringUtils.isEmpty(password)) {
			isSuccess = false;
			errorInfo = "手机号或密d码不能为空";
		}else {
			Boolean checkInfo = registerService.checkPhone(phoneNo);
			if (!checkInfo) {
				isSuccess = false;
				errorInfo = "手机号已被注册";
			}else {
				userMap.put("phoneNo", phoneNo);
				userMap.put("password", password);
				Boolean addInfo = registerService.add(userMap);
				if (!addInfo) {
					isSuccess = false;
					errorInfo = "添加用户失败";
				}
			}
		}
		if (isSuccess) {
			verifyService.deleteRegisterCode(phoneNo);
			OutputUtil.returnJsonp(request, response, isSuccess.toString());
		}else {
			OutputUtil.returnJsonp(request, response, isSuccess.toString());
			//OutputUtil.returnSuccess(response, isSuccess, errorInfo);
		}
	}

	 /**
	 * 手机验证
	 * @param request
	 * @param response
	 * @param phoneNo
	 * @author ServerZhang
	 * @date 2016年3月30日
	 */
	@RequestMapping("checkPhone/{phoneNo}")
	public void checkPhone(HttpServletRequest request,
			HttpServletResponse response, @PathVariable String phoneNo) {
		Boolean checkInfo = registerService.checkPhone(phoneNo);
		OutputUtil.returnJsonp(request, response, checkInfo.toString());
	}
	
	 /**
	 * 个人信息修改
	 * @param request
	 * @param response
	 * @param phoneNo
	 * @param field
	 * @param value
	 * @author ServerZhang
	 * @date 2016年3月17日
	 */
	@RequestMapping("update/{phoneNo}/{field}/{value}")
	public void updateInfor(HttpServletRequest request, 
			HttpServletResponse response,@PathVariable String phoneNo,
			@PathVariable String field, @PathVariable String value){
		Boolean isSuccess = registerService.update(phoneNo, field, value);
		OutputUtil.returnSuccess(response, isSuccess);
	}
	@RequestMapping("update/{phoneNo}")
	public void updateInfor(HttpServletRequest request, 
			HttpServletResponse response,@PathVariable String phoneNo){
		String userName = request.getParameter("userName");
		String nickName = request.getParameter("nickName");
		String sex = request.getParameter("sex");
		String area = request.getParameter("area");
		String bankName = request.getParameter("bankName");
		String accountBank = request.getParameter("accountBank");
		String account = request.getParameter("account");
		String idCard = request.getParameter("idCard");
		Map<String, Object> userMap = new HashMap<String, Object>();
		userMap.put("userName", userName);
		userMap.put("nickName", nickName);
		userMap.put("sex", sex);
		userMap.put("area", area);
		userMap.put("bankName", bankName);
		userMap.put("accountBank", accountBank);
		userMap.put("account", account);
		userMap.put("idCard", idCard);
		//头像处理
		String imgName = request.getParameter("imgName");
		String base64Str = request.getParameter("base64");
		Boolean uploadInfor = true;
		if (!StringUtils.isEmpty(imgName) && !StringUtils.isEmpty(base64Str)) {
			//图片数据
			String[] split = base64Str.split("base64,");
			String tempStr = split[1];
			String realStr = tempStr.substring(0, tempStr.length()-2);
			byte[] decode = MyBase64.decode(realStr);
			
			//上传图片及保存数据库
			Map<String, Object> others = new HashMap<String, Object>();
			others.put("saveType", PathManager.FILE_SAVE_TYPE_PHOTO);//必须的
			try {
				uploadInfor = fileUploadService.upload(ProjectInfor.PROJECT_NAME, phoneNo, 
						PathManager.FILE_SAVE_TYPE_PHOTO, imgName, decode, others);
			} catch (ParameterNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		Boolean isSuccess = registerService.update(phoneNo,userMap) && uploadInfor;
		OutputUtil.returnJsonp(request, response, isSuccess.toString());
	}
	 
	 /**
	 * 检查要修改的昵称或用户名是否已使用
	 * @param request
	 * @param response
	 * @param phoneNo
	 * @param name
	 * @author ServerZhang
	 * @date 2016年3月17日
	 */
	@RequestMapping("checkName/{phoneNo}/{name}")
	public void checkName(HttpServletRequest request, 
			HttpServletResponse response,@PathVariable String phoneNo,
			@PathVariable String name){
		Boolean isSuccess = registerService.checkUser(phoneNo, name);
		OutputUtil.returnSuccess(response, isSuccess);
	}
	
	/**
	 * 个人信息获取
	 * @param request
	 * @param response
	 * @param phoneNo
	 * @param field
	 * @author ServerZhang
	 * @date 2016年3月17日
	 */
	@RequestMapping("read/{phoneNo}/{field}")
	public void readField(HttpServletRequest request, 
			HttpServletResponse response,@PathVariable String phoneNo,
			@PathVariable String field){
		Object fieldInfo = registerService.read(phoneNo, field);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(field, fieldInfo);
		String json = JSONSerielizer.toJson(fieldInfo, null, null);
		OutputUtil.returnJsonp(request, response, json);
	}
	@RequestMapping("read/{phoneNo}")
	public void readInfor(HttpServletRequest request, 
			HttpServletResponse response,@PathVariable String phoneNo){
		Map<String, Object> map = registerService.read(phoneNo);
		OutputUtil.returnJsonp(request, response, JSONSerielizer.toJson(map, null, null));
	}
	
	 /**
	 * 修改密码
	 * @param request
	 * @param response
	 * @param phoneNo
	 * @param password
	 * @author ServerZhang
	 * @date 2016年3月18日
	 */
	@RequestMapping("pswUpdate/{phoneNo}/{password}")
	public void pswUpdate(HttpServletRequest request, 
			HttpServletResponse response,@PathVariable String phoneNo,
			@PathVariable String password){
		Boolean isSuccess = registerService.updatePswd(phoneNo, password);
		OutputUtil.returnSuccess(response, isSuccess);
	}
	 /**
	 * 获取用户头像路径
	 * @param request
	 * @param response
	 * @param phoneNo
	 * @author ServerZhang
	 * @date 2016年5月10日
	 */
	@RequestMapping("photo/{phoneNo}")
	public void photo(HttpServletRequest request, 
			HttpServletResponse response,@PathVariable String phoneNo){
		String photoPath = registerService.getPhotoPath(phoneNo);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("imgPath", photoPath);
		String json = JSONSerielizer.toJson(map, null, null);
		OutputUtil.returnJsonp(request, response, json);
	}
}
